package com.icesoft.base.manager.service.security;

import cn.hutool.core.util.StrUtil;
import com.icesoft.base.manager.base.BaseService;
import com.icesoft.base.manager.entity.security.RelSysRoleMenu;
import com.icesoft.base.manager.entity.security.RelSysUserRole;
import com.icesoft.base.manager.entity.security.SysMenu;
import com.icesoft.base.manager.model.MenuVo;
import com.icesoft.core.common.helper.tree.TreeUtils;
import com.icesoft.core.dao.criteria.QueryBuilder;
import com.icesoft.core.dao.criteria.SelectBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuService extends BaseService<SysMenu> {
    @Override
    protected List<SysMenu> find(QueryBuilder queryBuilder) {
        return super.find(queryBuilder.asc("sort").asc("id"));
    }

    @Override
    public List<SysMenu> findAll() {
        return find(QueryBuilder.get());
    }

    public List<SysMenu> findByUserId(int userId) {
        QueryBuilder queryBuilder = QueryBuilder.get()
                .distinct()
                .joinOn(RelSysRoleMenu.class, "rm", "menuId")
                .joinOn(RelSysUserRole.class, "ur", "roleId", "rm.roleId")
                .andEq("ur.userId", userId);
        return find(queryBuilder);
    }

    public SysMenu findMenuByPidAndTitle(int pid, String title) {
        return unique(QueryBuilder.get("pid", pid).andEq("title", title));
    }

    public List<SysMenu> findByRoleId(Integer roleId) {
        if (roleId == null || roleId == 0) {
            return new ArrayList<>();
        }
        QueryBuilder queryBuilder = QueryBuilder.get()
                .joinOn(RelSysRoleMenu.class, "rm", "menuId")
                .andEq("rm.roleId", roleId);
        return find(queryBuilder);
    }

    public List<String> findMenuUrl() {
        List<String> urls = findSelect(SelectBuilder.select("url"));
        return urls.stream().filter(StringUtils::hasText).collect(Collectors.toList());
    }

    /**
     * 转成带层级的菜单
     */
    public List<MenuVo> hierarchy(List<SysMenu> sysMenus) {
        List<MenuVo> menuInfo = new ArrayList<>();
        for (SysMenu e : sysMenus) {
            MenuVo menuVO = new MenuVo();
            menuVO.setId(e.getId());
            menuVO.setPid(e.getPid());
            menuVO.setHref(e.getUrl());
            menuVO.setTitle(e.getTitle());
            menuVO.setIcon(StrUtil.startWith(e.getIcon(), "fa-") ? "fa " + e.getIcon() : e.getIcon());
            menuVO.setTarget(e.getTarget() == null ? "_self" : e.getTarget());
            menuInfo.add(menuVO);
        }
        TreeUtils.hierarchy(menuInfo);
        return menuInfo;
    }
}
